<template>
  <div class="outerTemplate">
    <cart-header @delChose="delChose" @sao="searchCode">
      <div style="background: black;width: 1rem;height: 1rem"></div>
    </cart-header>

    <cart-list :allCheck="allCheck"
               :controltyp="controltyp"
               ref="cartList"
               @searchCode="searchCode"
               @changeChecked="changeChecked"
               @showSelectLadder="showSelectLadder"
               @showBuyMoreLadder="showBuyMoreLadder"
               @changeControltyp="changeControltyp"
               @getDiscountCoupon="getDiscountCoupon"
               @showChoseNum="showChoseNum"
               @initAllCheck="initAllCheck"
               @showBag="showBag"
               @showFree="showFree">

    </cart-list>

    <cart-modle ref="cartModle"
                backgroundColor="#f4f4f4">
      <cart-conpon
        :couponListCanBeUsed="couponListCanBeUsed"
        :isOffLine="true"
        @refreshData="refreshData"
        :couponListCanBeGet="couponListCanBeGet">
      </cart-conpon>

    </cart-modle>


    <cart-modle ref="ladderModle">
      <select-preset :ladderList="selectLadderList"
      >
      </select-preset>
    </cart-modle>

    <!--CartSelectGift-->
    <cart-modle ref="giftModle">
      <cart-select-gift
        :buyMoreLadderData="buyMoreLadderData"
      >
      </cart-select-gift>
    </cart-modle>

    <!--选择买赠-->
    <cart-modle ref="rebeatModle">
      <buy-more-list
        :buyMoreDetail="rebateEvery"
      >
      </buy-more-list>
    </cart-modle>

    <!--选择赠品-->
    <cart-modle ref="showFree">
      <buy-more-list
        :buyMoreDetail="showFreeData">
      </buy-more-list>
    </cart-modle>

    <!--选择购物袋-->
    <cart-modle ref="choseBag" :isBagCart="isBagCart">
      <chose-bag
        ref="choseBagList"
        :bagListDetail="bagListDetail">
      </chose-bag>
    </cart-modle>

    <cart-bottom :queryCart="queryCart"
                 :allCheck="allCheck"
                 @changeChecked="changeChecked"
                 @changeControltyp="changeControltyp">
    </cart-bottom>
  </div>
</template>

<script>
import CartHeader from './CartHeader';
import CartList from './CartList';
import CartBottom from './CartBottom';
import CartConpon from '@/real-components/CartConpon';
import CartModle from '@/real-components/CartMode';
import choseBag from './Components/ChoseBag';
import CartSelectGift from '../../real-components/CartRegular/CartSelectGift';
import { getPageTree, initDomTree } from '../../utils/getPageTree';
import SelectPreset from '../../real-components/CartRegular/CartSelectPreset';
import BuyMoreList from '../../real-components/CartRegular/BuyMoreList';
import { mapGetters } from 'vuex';
import { translateDetailData } from '@/utils/TranslateDetailDate';
import { Toast } from '@/utils/toast.js';
function isJSON(str, pass_object) {
	if (pass_object && isObject(str)) return true;
	str = str.replace(/\s/g, '').replace(/\n|\r/, '');
	if (/^\{(.*?)\}$/.test(str)) return /"(.*?)":(.*?)/g.test(str);
	if (/^\[(.*?)\]$/.test(str)) {
		return str
			.replace(/^\[/, '')
			.replace(/\]$/, '')
			.replace(/},{/g, '}\n{')
			.split(/\n/)
			.map(function(s) {
				return isJSON(s);
			})
			.reduce(function(prev, curr) {
				return !!curr;
			});
	}
	return false;
}

export default {
	data() {
		return {
			msg: '这是测试首页',
			page: 'cart',
			type: {
				list: 'list',
				header: 'header',
			},
			allCheck: false,
			controltyp: 0, // 1全选 2全取消  0 自由状态
			couponListCanBeUsed: null,
			couponListCanBeGet: null,
			selectLadderList: [],
			buyMoreLadderData: null,
			bagListDetail: [],
			rebateEvery: null,
			showFreeData: null,
			isGetNewDate: false,
			isBagCart:false
		};
	},
	components: {
		CartHeader,
		CartList,
		CartBottom,
		CartModle,
		SelectPreset,
		CartConpon,
		CartSelectGift,
		BuyMoreList,
		choseBag,
	},

	computed: {
		activeCartList() {
			return this.$store.getters['cjy/offLineAcitveData'];
		},
	},
	watch: {
		$route() {
			var code = this.$route.query.code;
			if (!code) {
				return;
			}
			this.addCart(code);
		},
	},
	methods: {
		//将扫码返回的barcode 添加到购物车
		async addCart(goodsCode, isFirst) {
			isFirst = isFirst || false;
			var cartList = this.$refs.cartList;
			if (goodsCode) {
				cartList && cartList.addGoods([{ goodsCode: goodsCode, goodsNum: 1 }], isFirst);
			} else if (isFirst) {
				this.queryCart();
			} else {
				Toast({
					message: '无效条形码',
					type: 'fail',
				});
			}
		},

		//更改全选控制状态
		changeControltyp(data) {
			this.controltyp = data;
		},

		refreshData() {
			this.$refs.cartList && this.$refs.cartList.queryRegularDetail();
		},
		// 点击删除按键
		delChose() {},
		delfromServe() {
			var confirm = {};
		},
		//更改选中状态
		changeChecked(data) {
			this.allCheck = data;
		},
		showModle(eleName) {
			this.$refs[eleName] && this.$refs[eleName].showModle();
		},
		//优惠券获取列表
		getDiscountCoupon(data) {
			this.showModle('cartModle');
			this.couponListCanBeUsed = data.couponListCanBeUsed;
			this.couponListCanBeGet = data.couponListCanBeGet;
		},
		// 展示优加赠列表
		showSelectLadder(data) {
			this.showModle('ladderModle');

			this.selectLadderList = data;
		},
		//展示可选礼品列表
		showBuyMoreLadder(data) {
			this.showModle('giftModle');
			this.buyMoreLadderData = data;
		},

		showChoseNum(data) {
			this.showModle('rebeatModle');
			this.rebateEvery = data;
		},
		showFree(data) {
			this.showModle('showFree');
			this.showFreeData = data;
		},

		showBag(data) {
			this.isBagCart = true
			this.showModle('choseBag');
			this.bagListDetail = data;
      this.$nextTick( () => {
        var choseBagList = this.$refs.choseBagList
        choseBagList.refresh()
      })
    },

		initAllCheck() {
			var data = this.activeCartList;
			this.allCheck = data.every(item => {
				var item = translateDetailData(item);
				return item.preorder;
			});
		},
		async queryCart() {
			var carList = this.$refs.cartList;
			carList && carList.animateLodding();
			carList && (await carList.queryCart());
			//申请购物车数据
		},
		//调出扫一扫
		searchCode() {
			let that = this;
			let className = undefined;
			let url = undefined;
			let opts = undefined;
			if (!cordova) {
				return;
			}
			cordova.exec(searchSuccess, searchFil, 'QCodePlugin', 'start', [className || {}, url || {}, opts || {}]);

			function searchFil() {
				Toast({
					message: '扫码失败！',
					iconClass: 'aui-iconfont aui-icon-close',
					duration: api.alertTime_2,
				});
			}

			function searchSuccess(request) {
				var req = isJSON(request) ? JSON.parse(request) : request;
				if (
					Object.prototype.toString.call(req) === '[object Number]' ||
					Object.prototype.toString.call(req) === '[object String]'
				) {
					//条形码
					that.addCart(req);
				} else {
					Toast({
						message: '扫码失败！',
						iconClass: 'aui-iconfont aui-icon-close',
						duration: api.alertTime_2,
					});
				}
			}
		},
	},
	beforeRouteEnter(to, from, next) {
		var fromName = from.name;
		next(vm => {
			vm.$nextTick(() => {
				var goodsCode = vm.$route.query.code || '';
				if (fromName == 'home' && goodsCode) {
					vm.addCart(goodsCode, true);
				} else {
					vm.queryCart();
				}
			});
		});
	},
	created() {
		this.$store.dispatch('cjy/clearOffLineDetail');
	},
	mounted() {},
	updated() {},
	beforeDestroy() {
		this.$store.dispatch('cjy/clearOffLineDetail');
	},
};
</script>

<style scoped>
.outerTemplate {
	width: 100%;
	height: 100%;
	position: relative;
	overflow: hidden;
  text-overflow: ellipsis;
  word-break:break-all;
  white-space: nowrap;
}
</style>
